package com.spring.demo.core.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.oxm.XmlMappingException;
import org.springframework.oxm.castor.CastorMarshaller;
import org.springframework.stereotype.Service;

import com.spring.demo.core.entity.BaseEntity;
import com.spring.demo.core.service.IOxmConverter;
import com.spring.demo.util.AppProperties;

@Service
public class OxmConverter implements IOxmConverter {

	@Autowired
	private CastorMarshaller marshaller;
	private static Logger logger = LoggerFactory.getLogger(OxmConverter.class);

	@Override
	public void saveObject(BaseEntity e) throws XmlMappingException,
			IOException {
		logger.debug("e.class {}", e.getClass());
		File file = getFile(e.getId(), e.getClass());
		FileOutputStream fos = new FileOutputStream(file);
		marshaller.marshal(e, new StreamResult(fos));
	}

	@Override
	@SuppressWarnings("unchecked")
	public <T> T getById(Long id, Class<T> c) throws XmlMappingException,
			IOException {
		File file = getFile(id, c);
		return (T) marshaller.unmarshal(new StreamSource(file));
	}

	private File getFile(Long id, Class<?> c) {
		String fileName = c.getSimpleName() + "_" + id + ".xml";
		File oxmPathDir = AppProperties.getOxmPathDir();
		File file = new File(oxmPathDir, fileName);
		return file;
	}

}
